﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Zhj.Common.Helpers;
using Zhj.Somethings.SampleService.Application.Cope;
using Zhj.Somethings.SampleService.Domain.Cope;
using Zhj.Somethings.SampleService.Domain.IRepository;
using Zhj.Somethings.SampleService.Repository;
using Zhj.Somethings.SampleService.Repository.Repository;

namespace Zhj.Somethings.SampleService.Host
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container. 
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //RegisterServices(this.GetType().Assembly, services);

            return InitIoC(services);
        }

        private IServiceProvider InitIoC(IServiceCollection services)
        {
            // var interfaceAssembly = RuntimeHelper.GetAssembly("Zhj.Somethings.SampleService.Application");

            var controllerAssembly = RuntimeHelper.GetAssembly("Zhj.Somethings.SampleService.Application");
            //过滤掉非接口及泛型接口
            var types = controllerAssembly.GetTypes().Where(t =>
            {
                var typeInfo = t.GetTypeInfo();
                return typeInfo.IsClass && !typeInfo.IsAbstract && !typeInfo.IsGenericType && t.IsAssignableFrom(typeof(Controller));
            });

            foreach (var type in types)
            {
                services.AddScoped(type);
            }

            return services.BuildServiceProvider();

        }

        private void RegisterServices(IServiceCollection services)
        {
            services.AddTransient<ICopeApplication, CopeApplicationImpl>();
            services.AddTransient<ICopeService, CopeServiceImpl>();
            services.AddTransient<IProductRepository, ProductRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}
